package com.motu.monstercity.server.game.logichandler;

import com.motu.monstercity.module.common.network.RequestParam;
import com.motu.monstercity.protocol.Common.PBUserData;
import com.motu.monstercity.protocol.CsGameMaintask.*;
import com.motu.monstercity.server.game.base.CommonUtils;
import com.motu.monstercity.server.game.base.GameConstant;
import com.motu.monstercity.server.game.base.ProtoDataUtils;
import com.motu.monstercity.server.game.commondata.bag.BagConstant;
import com.motu.monstercity.server.game.commondata.bag.Box;
import com.motu.monstercity.server.game.commondata.bag.ItemId;
import com.motu.monstercity.server.game.commondata.maintask.HonorReward;
import com.motu.monstercity.server.game.commondata.maintask.TaskDay;
import com.motu.monstercity.server.game.commondata.maintask.MainTaskConstant;
import com.motu.monstercity.server.game.commondata.maintask.TaskAchieve;
import com.motu.monstercity.server.game.commondata.system.SystemConstant;
import com.motu.monstercity.server.game.commondata.union.UnionConstant;
import com.motu.monstercity.server.game.log.LogType;
import com.motu.monstercity.server.game.log.ThinkingDataManager;
import com.motu.monstercity.server.game.logic.*;
import com.motu.monstercity.server.game.userdata.*;
import com.motu.vertx.module.utility.toolset.ErrorWord;
import com.motu.vertx.module.utility.toolset.Tool;
import io.vertx.core.json.JsonArray;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

public class MaintaskHandler {
	// CMD_GAME_MAINTASK_GET_REWARD = 73001; // 领取主线任务奖励
	public static Object CMD_GAME_MAINTASK_GET_REWARD(RequestParam clientParam) throws Exception {
		CSGameMaintaskGetRewardRequest request = CSGameMaintaskGetRewardRequest.parseFrom(clientParam.getData());
		CSGameMaintaskGetRewardResponse.Builder response = CSGameMaintaskGetRewardResponse.newBuilder();
		long userId = clientParam.getUserId();

		int taskAchieveId = request.getTaskAchieveId();
		TaskAchieve taskAchieve = MainTaskManager.getTaskAchieve(taskAchieveId);
		if (taskAchieve == null || !taskAchieve.isMainTask()) {
			return ErrorWord.NOT_DATA;
		}

		if (!MainTaskManager.isTaskComplete(userId, taskAchieve)) {
			return ErrorWord.WRONG_STATUS;// 进度值不达标
		}

		long taskId = MainTaskManager.getTaskId(taskAchieve.getTaskType(), taskAchieve.getParam());
		UserMainTask userMainTask = MainTaskManager.getUserMainTask(userId, taskId);
		if (userMainTask != null && Tool.isInList(userMainTask.getGetRewardArray(), taskAchieveId)) {
			return ErrorWord.REPEATED_OPERATION;// 重复领取
		}

		// 执行逻辑
		PBUserData.Builder pbUserData = response.getUserBuilder();
		UserInfo userInfo = GameUser.getUserInfo(userId);
		List<RewardItem> rewardItemList = CommonUtils.takeReawrdItemFromStr(taskAchieve.getReward());
		RewardManager.addReward(userInfo, rewardItemList, pbUserData, LogType.MAIN_TASK_REWARD);

		if (userMainTask == null) {
			userMainTask = new UserMainTask();
			userMainTask.putUserId(userId);
			userMainTask.putTaskId(taskId);
			JsonArray jsonArray = new JsonArray().add(taskAchieveId);
			userMainTask.putGetReward(jsonArray.toString());
			userMainTask.doCreate();
			ProtoDataUtils.updatePBUserData(pbUserData, userMainTask, true);
		} else {
			JsonArray jsonArray = userMainTask.getGetRewardArray();
			jsonArray.add(taskAchieveId);
			userMainTask.putGetReward(jsonArray.toString());
			userMainTask.update();
			ProtoDataUtils.updatePBUserData(pbUserData, userMainTask);
		}

		UserAffair userAffair = GameUser.getUserAffair(userId);
		userAffair.putMainTaskId(taskAchieveId);
		userAffair.update();
		pbUserData.getUserInfoBuilder().getUserAffairBuilder().setMainTaskId(taskAchieveId);

		if (MainTaskManager.isResetNumByTaskType(taskAchieve.getTaskType())) {// 某任务类型的进度值,是否在领取完奖励需要重置 如type<100
			UserTaskValue userTaskValue = MainTaskManager.getUserTaskValue(userId, taskAchieve);
			userTaskValue.putNum(0);
			userTaskValue.update();
			ProtoDataUtils.updatePBUserData(pbUserData, userTaskValue);
		}
		MainTaskManager.addTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_256, 1);// 主线任务完成几个，领取主线任务奖励时才会累计
		// 上报数数
		ThinkingDataManager.pushTaskFlowEvent(userInfo, 2, taskAchieveId, 2);

		return response;
	}

	//  CMD_GAME_MAINTASK_GET_REWARD_ACHIEVE = 73002; // 领取成就奖励
	public static Object CMD_GAME_MAINTASK_GET_REWARD_ACHIEVE(RequestParam clientParam) throws Exception {
		CSGameMaintaskGetRewardAchieveRequest request = CSGameMaintaskGetRewardAchieveRequest.parseFrom(clientParam.getData());
		CSGameMaintaskGetRewardAchieveResponse.Builder response = CSGameMaintaskGetRewardAchieveResponse.newBuilder();
		long userId = clientParam.getUserId();

		List<Integer> taskTypeList = request.getTaskTypeListList();

		PBUserData.Builder pbUserData = response.getUserBuilder();
		UserInfo userInfo = GameUser.getUserInfo(userId);
		List<RewardItem> rewardItemList = new ArrayList<>();// 奖励列表

		ConcurrentHashMap<Long, Long> taskValueMap = new ConcurrentHashMap<>();// 任务进度，缓存下来避免重复取usertaskvalue的数据

		for (int i=0; i<taskTypeList.size(); i++) {
			int taskType = taskTypeList.get(i);
			UserAchieve userAchieve = MainTaskManager.getUserAchieve(userId, taskType);
			JsonArray jsonArray = userAchieve.getGetRewardArray();// 领取记录

			boolean isUpdate = false;
			ConcurrentHashMap<Integer, TaskAchieve> taskAchieveList = MainTaskManager.getTaskAchieveList(taskType);// 获取某个task_type下的所有task_achieve配置
			if (taskAchieveList == null) {
				continue;
			}
			for (TaskAchieve taskAchieve : taskAchieveList.values()) {
				// 是主线任务，且未领取过的
				if (taskAchieve.isAchieveTask() && taskAchieve.getTaskType() == taskType && !Tool.isInList(jsonArray, taskAchieve.getId())) {
					long taskId = MainTaskManager.getTaskId(taskType, taskAchieve.getParam());
					long taskValue = 0;
					if (taskValueMap.containsKey(taskId)) {
						taskValue = taskValueMap.get(taskId);
					} else {
						taskValue = MainTaskManager.getTaskValue(userId, taskType, taskAchieve.getParam());
						taskValueMap.put(taskId, taskValue);// 缓存下来避免重复取值
					}
					if (taskValue >= taskAchieve.getNum()) {// 进度值达标
						jsonArray.add(taskAchieve.getId());
						isUpdate = true;
						CommonUtils.mergeItemList(rewardItemList, CommonUtils.takeReawrdItemFromStr(taskAchieve.getReward()));// 合并奖励

						// 上报数数
						ThinkingDataManager.pushTaskFlowEvent(userInfo, 3, taskAchieve.getId(), 2);
					}
				}
			}
			if (isUpdate) {
				userAchieve.putGetReward(jsonArray.toString());
				userAchieve.update();
				ProtoDataUtils.updatePBUserData(pbUserData, userAchieve);
			}
		}
		if (rewardItemList.size() > 0) {
			RewardManager.addReward(userInfo, rewardItemList, pbUserData, LogType.ACHIEVE_REWARD);
		}

		return response;
	}

	//  CMD_GAME_MAINTASK_GET_REWARD_DAYTASK = 73003; // 领取日常任务奖励和活跃度奖励
	public static Object CMD_GAME_MAINTASK_GET_REWARD_DAYTASK(RequestParam clientParam) throws Exception {
		CSGameMaintaskGetRewardDaytaskRequest request = CSGameMaintaskGetRewardDaytaskRequest.parseFrom(clientParam.getData());
		CSGameMaintaskGetRewardDaytaskResponse.Builder response = CSGameMaintaskGetRewardDaytaskResponse.newBuilder();
		long userId = clientParam.getUserId();

		int dayTaskId = request.getDayTaskId();
		TaskDay taskDay = MainTaskManager.getTaskDay(dayTaskId);
		if (taskDay == null) {
			return ErrorWord.NOT_DATA;
		}
		UserDayTask userDayTask = MainTaskManager.getUserDayTask(userId, taskDay.getTaskType());
		if (userDayTask == null || userDayTask.getNum() < taskDay.getNum()) {
			return ErrorWord.WRONG_STATUS;// 进度值不达标
		}
		JsonArray jsonArray = userDayTask.getGetRewardArray();// 领取记录
		if (Tool.isInList(jsonArray, dayTaskId)) {
			return ErrorWord.REPEATED_OPERATION;// 重复领取
		}

		// 执行逻辑
		PBUserData.Builder pbUserData = response.getUserBuilder();
		UserInfo userInfo = GameUser.getUserInfo(userId);
		List<RewardItem> rewardItemList = CommonUtils.takeReawrdItemFromStr(taskDay.getReward());
		RewardManager.addReward(userInfo, rewardItemList, pbUserData, LogType.DAY_TASK_REWARD, UnionConstant.UNION_GIFT_BOX_TYPE_1);

		jsonArray.add(dayTaskId);
		userDayTask.putGetReward(jsonArray.toString());
		userDayTask.update();
		ProtoDataUtils.updatePBUserData(pbUserData, userDayTask);

		// 上报数数
		ThinkingDataManager.pushTaskFlowEvent(userInfo, 1, dayTaskId, 2);

		if (taskDay.getActive() > 0) {// 有增加活跃度
			MainTaskManager.addTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_999, taskDay.getActive());
		}

		return response;
	}

	// CMD_GAME_MAINTASK_GET_REWARD_HONOR = 73004; // 领取荣誉奖励
	public static Object CMD_GAME_MAINTASK_GET_REWARD_HONOR(RequestParam clientParam) throws Exception {
		CSGameMaintaskGetRewardHonorRequest request = CSGameMaintaskGetRewardHonorRequest.parseFrom(clientParam.getData());
		CSGameMaintaskGetRewardHonorResponse.Builder response = CSGameMaintaskGetRewardHonorResponse.newBuilder();
		long userId = clientParam.getUserId();

		int dbid = request.getHonorDbid();



		HonorReward honorReward = MainTaskManager.getHonorReward(dbid);
		if (honorReward == null) {
			return ErrorWord.NOT_DATA;
		}

		UserInfo userInfo = GameUser.getUserInfo(userId);

		UserHonor userHonor = MainTaskManager.getUserHonor(userId, honorReward.getHonorType());
		JsonArray jsonArray = userHonor == null ? new JsonArray() : userHonor.getGetRewardArray();//领取记录
		if (Tool.isInList(jsonArray, dbid)) {
			return ErrorWord.REPEATED_OPERATION;// 重复领取
		}
		if (honorReward.isServerHonor()) {// 全服荣誉,进度取全服的
			ServerHonor serverHonor = MainTaskManager.getServerHonor(userInfo.getServerId(), honorReward.takeHonorId());
			if (serverHonor == null || serverHonor.getUserId() == 0) {
				return ErrorWord.WRONG_STATUS;// 进度值不达标
			}
		} else if (honorReward.isUnionHonor()) {
			UserUnion userUnion = UnionManager.getUserUnion(userId);
			if (userUnion.getUnionId() == 0) {
				return ErrorWord.NOT_DATA_1; // 未加入联盟
			}
			UnionInfo unionInfo = UnionManager.getUnionInfo(userUnion.getUnionId());
			if (unionInfo == null) {
				return ErrorWord.NOT_DATA_2; // 联盟不存在
			}
			UnionHonor unionHonor = MainTaskManager.getUnionHonor(userUnion.getUnionId(), honorReward.getHonorType());
			if (unionHonor == null || unionHonor.getNum() < honorReward.getNum()) {
				return ErrorWord.WRONG_STATUS;// 进度值不达标
			}
		} else {
			if (userHonor == null || userHonor.getNum() < honorReward.getNum()) {
				return ErrorWord.WRONG_STATUS;// 进度值不达标
			}
		}

		// 执行逻辑
		PBUserData.Builder pbUserData = response.getUserBuilder();
		RewardManager.addReward(userInfo, CommonUtils.takeReawrdItemFromStr(honorReward.getReward()), pbUserData, LogType.HONOR_REWARD);

		jsonArray.add(dbid);
		if (userHonor == null) {
			userHonor = new UserHonor(userId, honorReward.getHonorType());
			userHonor.putGetReward(jsonArray.toString());
			userHonor.doCreate();
			ProtoDataUtils.updatePBUserData(pbUserData, userHonor, true);
		} else {
			userHonor.putGetReward(jsonArray.toString());
			userHonor.update();
			ProtoDataUtils.updatePBUserData(pbUserData, userHonor);
		}

		return response;
	}

	// CMD_GAME_MAINTASK_HONOR_MAIN_INFO = 73005; // 读取全部荣誉进度[2]每次打开请求
	public static Object CMD_GAME_MAINTASK_HONOR_MAIN_INFO(RequestParam clientParam) throws Exception {
		CSGameMaintaskHonorMainInfoRequest request = CSGameMaintaskHonorMainInfoRequest.parseFrom(clientParam.getData());
		CSGameMaintaskHonorMainInfoResponse.Builder response = CSGameMaintaskHonorMainInfoResponse.newBuilder();
		long userId = clientParam.getUserId();

		int honorType = request.getHonorType();
		// 执行逻辑
		UserInfo userInfo = GameUser.getUserInfo(userId);
		for (HonorReward honorReward : MainTaskManager.getHonorRewardMap().values())  {
			if (honorReward.isServerHonor() && honorReward.getHonorType() == honorType) {
				ServerHonor serverHonor = MainTaskManager.getServerHonor(userInfo.getServerId(), honorReward.takeHonorId());
				if (serverHonor != null) {
					response.putServerHonor(serverHonor.getHonorId(), serverHonor.takeInitBuilder().build());
				}
			}
		}

		return response;
	}

	// CMD_GAME_MAINTASK_GET_REWARD_HONOR_ONEKEY = 73006; // 领取某个类型的所有荣誉奖励
	public static Object CMD_GAME_MAINTASK_GET_REWARD_HONOR_ONEKEY(RequestParam clientParam) throws Exception {
		CSGameMaintaskGetRewardHonorOnekeyRequest request = CSGameMaintaskGetRewardHonorOnekeyRequest.parseFrom(clientParam.getData());
		CSGameMaintaskGetRewardHonorOnekeyResponse.Builder response = CSGameMaintaskGetRewardHonorOnekeyResponse.newBuilder();
		long userId = clientParam.getUserId();

		int honorType = request.getHonorType();//
		PBUserData.Builder pbUserData = response.getUserBuilder();
		UserInfo userInfo = GameUser.getUserInfo(userId);
		UserHonor userHonor = MainTaskManager.getUserHonor(userId, honorType);
		JsonArray jsonArray = userHonor == null ? new JsonArray() : userHonor.getGetRewardArray();//领取记录
		boolean isUpdate = false;
		for (HonorReward honorReward : MainTaskManager.getHonorRewardMap().values()) {
			if (honorReward.getHonorType() == honorType && !Tool.isInList(jsonArray, honorReward.getId())) {
				boolean isCanGet = false;
				if (honorReward.isServerHonor()) {
					ServerHonor serverHonor = MainTaskManager.getServerHonor(userInfo.getServerId(), honorReward.takeHonorId());
					if (serverHonor != null && serverHonor.getUserId() > 0) {
						isCanGet = true;
					}
				} else {
					if (userHonor != null && userHonor.getNum() >= honorReward.getNum()) {
						isCanGet = true;
					}
				}
				if (isCanGet) {// 领取
					jsonArray.add(honorReward.getId());
					isUpdate = true;
					RewardManager.addReward(userInfo, CommonUtils.takeReawrdItemFromStr(honorReward.getReward()), pbUserData, LogType.HONOR_REWARD);
				}
			}
		}
		if (isUpdate) {
			if (userHonor == null) {
				userHonor = new UserHonor(userId, honorType);
				userHonor.putGetReward(jsonArray.toString());
				userHonor.doCreate();
				ProtoDataUtils.updatePBUserData(pbUserData, userHonor, true);
			} else {
				userHonor.putGetReward(jsonArray.toString());
				userHonor.update();
				ProtoDataUtils.updatePBUserData(pbUserData, userHonor);
			}
		}
		return response;
	}

	//  CMD_GAME_MAINTASK_GET_REWARD_CITYTASK = 73007; // 领取城市任务的奖励
	public static Object CMD_GAME_MAINTASK_GET_REWARD_CITYTASK(RequestParam clientParam) throws Exception {
		CSGameMaintaskGetRewardCitytaskRequest request = CSGameMaintaskGetRewardCitytaskRequest.parseFrom(clientParam.getData());
		CSGameMaintaskGetRewardCitytaskResponse.Builder response = CSGameMaintaskGetRewardCitytaskResponse.newBuilder();
		long userId = clientParam.getUserId();

		int taskAchieveId = request.getTaskAchieveId();
		TaskAchieve taskAchieve = MainTaskManager.getTaskAchieve(taskAchieveId);
		if (taskAchieve == null || !taskAchieve.isCityTask()) {
			return ErrorWord.NOT_DATA;
		}

		if (!MainTaskManager.isTaskComplete(userId, taskAchieve)) {
			return ErrorWord.WRONG_STATUS;// 进度值不达标
		}

		UserCityTaskReward userCityTaskReward = MainTaskManager.getUserCityTaskReward(userId, taskAchieve.getTaskType());
		if (userCityTaskReward != null && Tool.isInList(userCityTaskReward.getGetRewardArray(), taskAchieveId)) {
			return ErrorWord.REPEATED_OPERATION;// 重复领取
		}

		// 执行逻辑
		PBUserData.Builder pbUserData = response.getUserBuilder();
		UserInfo userInfo = GameUser.getUserInfo(userId);
		MainTaskManager.getCityTaskReward(pbUserData, userInfo, taskAchieve, userCityTaskReward, false);// 领取城市任务奖励，并记录领取记录

		// 上报数数
		ThinkingDataManager.pushTaskFlowEvent(userInfo, 3, taskAchieveId, 2);

		return response;
	}
}
